package com.house.rent.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.FrameLayout;

import com.base.lib.mvp.present.BasePresenter;
import com.base.lib.widget.CustomWebView;


public class WebActivity extends BaseActivity {

    private static final String TITLE = "title";
    private static final String URL = "url";

    private WebView mWebView;

    private String mUrl;
    private String mTitle;

    public static void start(Context context, String title, String url) {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra(TITLE, title);
        intent.putExtra(URL, url);
        context.startActivity(intent);
    }

    @Override
    public void initIntent(Intent intent) {
        super.initIntent(intent);
        mTitle = intent.getStringExtra(TITLE);
        mUrl = intent.getStringExtra(URL);
    }

    @Override
    public void initTop() {
        if (TextUtils.isEmpty(mTitle)) {
            mTitle = "";
        }
        setTitle(mTitle);

    }

    @Override
    protected int getLayoutResId() {
        return 0;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        //用XML引入，仍然会内存泄露https://stackoverflow.com/questions/3130654/memory-leak-in-webview
        mWebView = new CustomWebView(getApplicationContext());
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        mWebView.setLayoutParams(params);
        setContentView(mWebView);
    }


    @Override
    public void initData() {
        mWebView.loadUrl(mUrl);
    }

    @Override
    public void initListeners() {

    }

    @Override
    protected BasePresenter initPresenter() {
        return null;
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mWebView) {
            //解除webView与父控件的依附关系
            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.removeAllViews();
            mWebView.setTag(null);
            mWebView.clearHistory();
            mWebView.loadUrl("about:blank");
            mWebView.setVisibility(View.GONE);
            mWebView.destroy();
            mWebView = null;
        }
    }
}
